<script setup lang="ts">
import {ref} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {login} from "@/api/user";
import {ElMessage} from "element-plus";
import router from "@/router";

const formRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  }
  if (value.length < 6 || value.length > 12) {
    callback(new Error('数字，英文，下划线 6至12位'))
  }
  callback()
}
const rules = ref<FormRules<typeof formData>>({
  account: [{required: true, message: '账号不能为空', trigger: 'blur'}],
  password: [{required: true, validator: validatePass, trigger: 'blur'}],
})

const formData = ref({
  account: '',
  password: '',
})
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl)
    return
  formEl.validate((valid) => {
    if (valid) {
      const data = {
        account: formData.value.account,
        password: formData.value.password
      }
      login(data)
          .then((res: any) => {
            const {code, msg} = res
            console.log(res)
            if (code !== 0) {
              ElMessage.error(msg)
              return
            }
            const {token} = res
            localStorage.setItem('token', token)
            router.push('/')
          })
          .catch((err) => {
            console.log(err)
          })

      return
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<template>
  <div class="container">
    <div class="form-container">
      <el-form
          ref="formRef"
          :model="formData"
          status-icon
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="formData.account" placeholder="请输入账户" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)">登录
          </el-button>
          <el-button @click="resetForm(formRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom right, white, pink);
  display: flex;
  align-items: center;
  justify-content: center;

  .form-container {
    width: 450px;
  }
}
</style>